import { fetchUserCenter } from '../../services/usercenter/fetchUsercenter';
import { getCliInfo } from '../../services/usercenter/index';
import { fetchShopMapInfos } from '../../services/usercenter/fetchShopMap'
import Toast from 'tdesign-miniprogram/toast/index';

const menuData = [
  [
    {
      title: '收货地址',
      tit: '',
      url: '',
      type: 'address',
    },
    {
      title: '优惠券',
      tit: '',
      url: '',
      type: 'coupon',
    },
  ],
  [
    {
      title: '公司介绍',
      tit: '',
      url: '',
      type: 'company',
    },
    {
      title: '线下门店',
      tit: '',
      url: '',
      type: 'offline',
    },
    {
      title: '帮助中心',
      tit: '',
      url: '',
      type: 'help-center',
    },
    {
      title: '客服热线',
      tit: '',
      url: '',
      type: 'service',
      icon: 'service',
    },
  ],
];

const getDefaultData = () => ({
  showMakePhone: false,
  userInfo: {
    avatarUrl: '',
    nickName: '正在登录...',
    phoneNumber: '',
  },
  mapInfo: {},
  menuData,
  customerServiceInfo: {},
  currAuthStep: 1,
  showKefu: true,
  versionNo: '',
});

Page({
  data: getDefaultData(),

  onLoad() {
    this.getVersionInfo();
  },

  onShow() {
    this.getTabBar().init();
    this.init();
  },
  onPullDownRefresh() {
    this.init();
  },

  init() {
    this.fetUseriInfoHandle();
  },

  fetUseriInfoHandle() {
    const _this = this;
    getCliInfo().then(res => {
      console.log(res);
      const userInfo = res.data;
      _this.setData({ userInfo });
    })
    fetchUserCenter().then(
      ({
        countsData,
        customerServiceInfo,
      }) => {
        // eslint-disable-next-line no-unused-expressions
        menuData?.[0].forEach((v) => {
          countsData.forEach((counts) => {
            if (counts.type === v.type) {
              // eslint-disable-next-line no-param-reassign
              v.tit = counts.num;
            }
          });
        });
        this.setData({
          menuData,
          // orderTagInfos: info,
          customerServiceInfo,
          currAuthStep: 2,
        });
        wx.stopPullDownRefresh();
      },
    );
  },

  onClickCell({ currentTarget }) {
    const { type } = currentTarget.dataset;

    switch (type) {
      case 'address': {
        wx.navigateTo({ url: '/pages/usercenter/address/list/index' });
        break;
      }
      case 'service': {
        this.openMakePhone();
        break;
      }
      case 'help-center': {
        this.toastMessage("你点击了帮助中心");
        break;
      }
      case 'offline': {
        this.handleMarkertap();
        break;
      }
      case 'company': {
        this.toastMessage("你点击了公司介绍");
        break;
      }
      case 'coupon': {
        wx.navigateTo({ url: '/pages/coupon/coupon-list/index' });
        break;
      }
      default: {
        this.toastMessage("未知跳转");
        break;
      }
    }
  },

  handleToastMessage({ detail }) {
    this.toastMessage(detail.message);
  },

  toastMessage(message) {
    Toast({
      context: this,
      selector: '#t-toast',
      message: message,
      icon: '',
      duration: 1000,
    });
  },

  jumpNav(e) {
    const status = e.detail.tabType;

    if (status === 0) {
      wx.navigateTo({ url: '/pages/order/after-service-list/index' });
    } else {
      wx.navigateTo({ url: `/pages/order/order-list/index?status=${status}` });
    }
  },

  jumpAllOrder() {
    wx.navigateTo({ url: '/pages/order/order-list/index' });
  },

  openMakePhone() {
    this.setData({ showMakePhone: true });
  },

  closeMakePhone() {
    this.setData({ showMakePhone: false });
  },

  call() {
    wx.makePhoneCall({
      phoneNumber: this.data.customerServiceInfo.servicePhone,
    });
  },

  gotoUserEditPage() {
    const { currAuthStep } = this.data;
    if (currAuthStep === 2) {
      // wx.navigateTo({ url: '/pages/usercenter/person-info/index' });
      wx.navigateTo({ url: '/pages/usercenter/userinfo-edit/index' });
    } else {
      this.fetUseriInfoHandle();
    }
  },

  getVersionInfo() {
    const versionInfo = wx.getAccountInfoSync();
    const { version, envVersion = __wxConfig } = versionInfo.miniProgram;
    this.setData({
      versionNo: envVersion === 'release' ? version : envVersion,
    });
  },

  handleMarkertap() {
    const mapInfo = this.data.mapInfo;
    if (mapInfo && mapInfo.address) {
      this.openLocation();
    } else {
      fetchShopMapInfos().then(
        ({ addressInfos }) => {
          let addressInfo = addressInfos[0];
          const info = {
            longitude: addressInfo.location.lng,//中心经度
            latitude: addressInfo.location.lat,//中心纬度
            markers: [
              {
                id: 'wx_sprongdoor_point',
                longitude: addressInfo.location.lng,//经度
                latitude: addressInfo.location.lat,//纬度
                title: addressInfo.name,
                display: 'ALWAYS'
              }
            ],//标记点列表
            address: addressInfo.address,
            name: addressInfo.name
          }
          this.setData({ mapInfo: info });
          this.openLocation();
        }
      )
    }
  },
  openLocation() {
    const mapInfo = this.data.mapInfo;
    wx.openLocation({
      latitude: mapInfo.latitude,
      longitude: mapInfo.longitude,
      scale: 16,
      name: mapInfo.address,// 目的地
      success: (res) => {
        console.log('open location map success.. ', res);
      },
      fail: (err) => {
        console.log('open location map fail... ', err);
      }
    })
  }
});
